
library(tidyverse)
library(modelsummary)

# 0) Prepare data ####

if(!file.exists("./clean_data/pela.rds")){
load("./nonesharable_data/df.RData") 


pela <- df %>%
  dplyr::select(country, district, party, year, country_year, contains("_agreement"), age, gender, educ, inc, gov_opp, party_short, left_right, msch, lgnic) %>% 
  mutate(diff_useu = us_agreement - eu_agreement,
         diff_uspa = us_agreement - pacific_agreement,
         diff_usal = us_agreement - alba_agreement,
         diff_eupa = eu_agreement - pacific_agreement,
         diff_eual = eu_agreement - alba_agreement,
         diff_paal = pacific_agreement - alba_agreement,
         gov_opp = factor(gov_opp,
                          levels = c("Opposition", "Government")),
         country_short = countrycode::countrycode(country, "country.name", "iso3c")) %>% 
  dplyr::left_join(., readRDS("./nonesharable_data/unga_clean.RDS") %>% 
                     select(country_short = country_short2, year, dist_avg) %>% 
                     mutate(country_short = ifelse(country_short == "URU", "URY",
                                                   ifelse(country_short == "PAR", "PRY",
                                                          ifelse(country_short == "HON", "HND",
                                                                 ifelse(country_short == "GUA", "GTM",
                                                                        ifelse(country_short == "COS", "CRI", country_short)))))),
                   by = c("country_short", "year")) %>% 
  dplyr::left_join(., readRDS("./nonesharable_data/trade_clean.RDS") %>% 
                     dplyr::filter(country %in% unique(df$country_short), flow == "X", !is.na(agreement), agreement != "WLD") %>% 
                     pivot_wider(., id_cols = c(year, flow, country), names_from = agreement, values_from = total_trade) %>% 
                     mutate(shareuseu = log(USA / EU),
                            shareusal = log(USA / ALBA),
                            shareuspa = log(USA / PA),
                            shareeupa = log(EU / PA),
                            shareeual = log(EU / ALBA),
                            sharepaal = log(PA / ALBA),
                            year = year + 1) %>% 
                     ungroup() %>% 
                     select(country_short = country, year, contains("share")),
                   by = c("country_short", "year"))

saveRDS(pela, "clean_data/pela.rds")
rm(list = ls())
}

pela <- readRDS("clean_data/pela.rds")

# 1) Figure 4 ####

rbind(pela %>% 
        select(country_short, diff_useu, diff_uspa, diff_usal),
      pela %>% 
        select(country_short, diff_useu, diff_uspa, diff_usal) %>% 
        mutate(country_short = "OVR")) %>% 
  mutate(country_short = factor(country_short,
                                levels = c("OVR", "ARG", "BOL", "BRA",
                                           "CHL", "COL", "CRI", "DOM",
                                           "ECU", "GTM", "HND", "MEX",
                                           "NIC", "PAN", "PER", "PRY",
                                           "SLV", "URY", "VEN"))) %>% 
  drop_na() %>%
  group_by(country_short) %>%
  summarise(mean_useu = mean(diff_useu),
            se_useu = plotrix::std.error(diff_useu),
            mean_uspa = mean(diff_uspa),
            se_uspa = plotrix::std.error(diff_uspa),
            mean_usal = mean(diff_usal),
            se_usal = plotrix::std.error(diff_usal)) -> desc

dplyr::left_join(desc %>% 
                   select(country_short, contains("mean_")) %>% 
                   pivot_longer(cols = mean_useu:mean_usal, names_to = "var", values_to = "mean") %>% 
                   mutate(var = gsub("mean_", "", var)),
                 desc %>% 
                   select(country_short, contains("se_")) %>% 
                   pivot_longer(cols = se_useu:se_usal, names_to = "var", values_to = "se") %>% 
                   mutate(var = gsub("se_", "", var)),
                 by = c("country_short", "var")) %>% 
  mutate(var = factor(var,
                      levels = c("useu", "uspa", "usal"),
                      labels = c("US-EU", "US-PA", "US-AL"))) %>% 
  ggplot(., aes(x = forcats::fct_rev(country_short),
                y = mean,
                ymin = mean - 1.96*se,
                ymax = mean + 1.96*se)) + 
  geom_pointrange() +
  geom_hline(yintercept = 0, lty = "dotted") +
  coord_flip() + 
  theme_minimal() +
  labs(x = "Country", y = "Mean Preferences for Trade Partners") +
  facet_grid(~var) +
  NULL

ggsave("figures/Figure4.png", dpi = 600,
       width = 20, 
       height = 12, unit = "cm")

# 2) Table 3 ####

m_useu <- lme4::lmer(diff_useu ~ msch + lgnic + dist_avg + left_right + shareuseu + age + gender + educ + inc + gov_opp + (1 | district) + (1 | country_year), pela)
m_uspa <- lme4::lmer(diff_uspa ~ msch + lgnic + dist_avg + left_right + shareuspa + age + gender + educ + inc + gov_opp + (1 | district) + (1 | country_year), pela)
m_usal <- lme4::lmer(diff_usal ~ msch + lgnic + dist_avg + left_right + shareusal + age + gender + educ + inc + gov_opp + (1 | district) + (1 | country_year), pela)

texreg::screenreg(list(m_useu, m_uspa, m_usal),
                  custom.model.names = c("US-EU", "US-PA", "US-AL"))

texreg::htmlreg(list(m_useu, m_uspa, m_usal), 
                beside = T, 
                file = "./tables/table3.html", 
                single.row = F, 
                custom.model.names = c("Model 3", "Model 4", "Model 5"),
                leading.zero = T, 
                custom.coef.map = list("(Intercept)" = "Intercept",
                                       "msch" = "Mean years of schooling",
                                       "lgnic" = "GNIpc (region, log)",
                                       "dist_avg" = "Agreement in UNGA voting",
                                       "left_right" = "Political ideology",
                                       "shareuseu" = "Relative trade ties",
                                       "age" = "Age",
                                       "genderfemale" = "Gender (female)",
                                       "educPrimary" = "Primary education",
                                       "educSecondary" = "Secundary education",
                                       "educTertiary" = "Tertiary education",
                                       "inc1000-4000 USD" = "Income (1000-4000 USD)",
                                       "inc4000-7000 USD" = "Income (4000-7000 USD)",
                                       "inc7000-10000 USD" = "Income (7000-10000 USD)",
                                       "incMore than 10000 USD" = "Income > 10000 USD)",
                                       "gov_oppGovernment" = "Government",
                                       "shareuspa" = "Relative trade ties",
                                       "shareusal" = "Relative trade ties"))
